<?php

namespace pmvc\mvc\controller;

use pmvc\mvc\Controller;
use pmvc\mvc\Dispatcher;
use pmvc\mvc\Model;
use pmvc\mvc\Request;
use pmvc\mvc\Response;

class BaseFormController
	implements Controller {
	
	public $formView	= FALSE;
	public $errorView	= FALSE;
	public $successView	= FALSE;
	
	public function isFormSubmission(Request $request, Response $response) {
		return ($_SERVER["REQUEST_METHOD"]=="POST");
	}
	
	public function populateModel(Request $request, Response $response, FormErrors $errors) {
		if ($errors->hasErrors()) {
			$response->getModel()->set("formErrors", $errors->get());
		}
	}
	
	public function showForm(Request $request, Response $response, FormErrors $errors) {
		\pmvc\log\Log::trace("BaseFormController::showForm()");
		$this->populateModel($request, $response, $errors);
		return $this->formView;
	}
	
	public function validateForm(Request $request, Response $response, FormErrors $errors) {
		\pmvc\log\Log::trace("BaseFormController::validateForm()");
		return TRUE;
	}
	
	public function showValidationError(Request $request, Response $response, FormErrors $errors) {
		\pmvc\log\Log::trace("BaseFormController::showValidationError()");
		$this->populateModel($request, $response, $errors);
		return $this->errorView;
	}
	
	public function processForm(Request $request, Response $response, FormErrors $errors) {
		\pmvc\log\Log::trace("BaseFormController::processForm()");
		return TRUE;
	}
	
	public function showProcessError(Request $request, Response $response, FormErrors $errors) {
		\pmvc\log\Log::trace("BaseFormController::showProcessError()");
		$this->populateModel($request, $response, $errors);
		return $this->errorView;
	}
	
	public function showSuccess(Request $request, Response $response, FormErrors $errors) {
		\pmvc\log\Log::trace("BaseFormController::showSuccess()");
		return $this->successView;
	}
	
	/**
	 * {@inheritDoc}
	 */
    public final function handleRequest(Request $request, Response $response) {

    	// create form errors object
    	$errors = new FormErrors();
    	
    	// send to formView
    	if (!$this->isFormSubmission($request, $response, $errors)) {
    		return $this->showForm($request, $response, $errors);
    		
    	// proccess form submission
    	} else if (!$this->validateForm($request, $response, $errors)) {
    		return $this->showValidationError($request, $response, $errors);
    			
    	// proccess form submission
    	} else if (!$this->processForm($request, $response, $errors)) {
    		return $this->showProcessError($request, $response, $errors);
    		
    	// submission was successful
    	} else {
    		return $this->showSuccess($request, $response, $errors);
    	}
    }

}

?>